package com.example.im.ui.activity

import android.content.Intent
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import com.example.im.common.Enumerate
import com.example.im.R
import com.example.im.callback.OnClickUserListener
import com.example.im.common.ImApplication
import com.example.im.entity.EventBusData
import com.example.im.ui.fragment.*
import com.example.im.common.Constants
import com.example.im.entity.ChatRecordLast
import com.example.im.entity.FriendOrRoom
import com.example.im.mvp.presenter.UserPresenter
import com.example.im.mvp.view.IUserView
import com.example.im.ui.abstracts.AbstractBaseActivity
import kotlinx.android.synthetic.main.include_toolbar.*
import org.greenrobot.eventbus.EventBus
import org.jivesoftware.smack.roster.packet.RosterPacket

class UserActivity : AbstractBaseActivity<UserPresenter>(), IUserView, OnClickUserListener {

    private var mOnToUserSearchFragment: OnToUserSearchFragment? = null

    interface OnToUserSearchFragment {
        fun onSearchFriendGood(friends: MutableList<FriendOrRoom>)
    }

    override val layoutId: Int
        get() = R.layout.activity_user

    override fun onAttachFragment(fragment: Fragment) {
        super.onAttachFragment(fragment)
        when (fragment) {
            is UserCentreFragment -> tv_toolbar_title.text = "好友信息"
            is UserSearchFragment -> {
                tv_toolbar_title.text = "好友搜索"
                mOnToUserSearchFragment = fragment
            }
            is UserAddToFragment -> tv_toolbar_title.text = "好友添加"
        }
    }

    override fun initView() {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        val serializable = intent.getSerializableExtra(Constants.BUNDLE_T0_USER_DATA)
        val transaction = supportFragmentManager.beginTransaction()
        if (serializable == null) {
            transaction.replace(R.id.frame_layout, UserSearchFragment.newInstance())
        } else {
            val friend = serializable as FriendOrRoom
            transaction.replace(R.id.frame_layout, UserCentreFragment.newInstance(friend))
        }
        transaction.commit()
    }

    override fun initPresenter() {
        mPresenter = UserPresenter(this, this)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home -> onBackPressed()
        }
        return super.onOptionsItemSelected(item)
    }

    /**
     * 发送聊天-点击事件
     * */
    override fun onClickSendChat(view: View, friend: FriendOrRoom) {

        val intent = Intent(this, ChatActivity::class.java)
        intent.putExtra(Constants.BUNDLE_T0_CHAT_DATA, friend)
        startActivity(intent)
        finish()
    }

    /**
     * 删除聊天数据-点击事件
     * */
    override fun onClickClearChat(view: View, friend: FriendOrRoom) {
        val dialog = AlertDialog.Builder(this)
            .setTitle(friend.nickname)
            .setMessage("是否删除该用户聊天记录")
            .setPositiveButton("确定") { _, _ ->
                //通知聊天页面更新
                ImApplication.appDatabase().chatRecordLastDao()
                    .delete(friend.id)
                val busData = EventBusData(
                    Enumerate.Handle.list_chat, Enumerate.Action.list_delete, friend
                )
                EventBus.getDefault().post(busData)
            }
            .setNegativeButton("取消", null)
        dialog.show()
    }

    /**
     *删除好友-点击事件
     * */
    override fun onClickDelete(view: View, friend: FriendOrRoom) {

        val dialog = AlertDialog.Builder(this)
            .setTitle(friend.nickname)
            .setMessage("是否删除该用户")
            .setPositiveButton("确定") { _, _ ->
                mPresenter!!.userDelete(friend)
            }
            .setNegativeButton("取消", null)
        dialog.show()
    }

    /**
     * 用户搜索-点击事件
     * */
    override fun onClickSearch(view: View, userId: String) {
        mPresenter!!.userSearch(userId)
    }

    /**
     * 用户条目点击
     * */
    override fun onClickFriendItem(view: View, friend: FriendOrRoom) {
        val friendDB = ImApplication.appDatabase().friendOrRoomDao()
            .selectFriendOrRoomByName(friend.account)
        val transaction = supportFragmentManager.beginTransaction()
        if (friendDB != null && friendDB.sub == RosterPacket.ItemType.both.ordinal) {
            transaction.add(R.id.frame_layout, UserCentreFragment.newInstance(friendDB))
        } else {
            transaction.add(R.id.frame_layout, UserAddToFragment.newInstance(friend))
        }
        transaction.addToBackStack(null)
        transaction.commit()
    }

    /**
     * 搜索到的用户结果
     * */
    override fun onSearchFriendGood(friends: MutableList<FriendOrRoom>) {
        mOnToUserSearchFragment!!.onSearchFriendGood(friends)
    }

    /**
     * 发送添加请求
     * */
    override fun onClickAddTo(view: View, friend: FriendOrRoom) {
        mPresenter!!.userAddition(friend.account!!, friend.nickname!!)
    }


    override fun onAdditionSuccess() {
        finish()
    }

    /**
     * 删除好友成功调用
     * */
    override fun onRemoverSuccess(friend: FriendOrRoom) {
        //删除数据
        ImApplication.appDatabase()
            .friendOrRoomDao().delete(friend)
        val busData1 = EventBusData(
            Enumerate.Handle.list_chat, Enumerate.Action.list_delete, friend
        )
        EventBus.getDefault().post(busData1)
        val busData2 = EventBusData(
            Enumerate.Handle.list_friend, Enumerate.Action.list_delete, friend
        )
        EventBus.getDefault().post(busData2)
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        this.finish()
    }

}